<?php
namespace App\Http\Controllers\Front;
/**
 *@author Joker
 *教程->章节->课程
 * teaches 教程
 * chapter 章节
 * stcontent 课程
 */
use App\Models\Ads;
use App\Models\Comments;
use App\Models\Tags;
use App\Models\Teaches;
use App\Models\TeachesChapter;
use App\Models\TeachesContent;
use App\Models\UserScore;
use App\Models\UserScoreStream;
use App\Models\UserStudy;
use App\Models\UserTeaches;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
class StudyController extends MasterController
{
    protected $nav;
    protected $ads;
    protected $teachesHots;
    
    public function __construct()
    {
        parent::__construct();
        $this->nav = 2;
        $this->teachesHots = Teaches::where(['is_validate' => 1, 'is_hot' => 1])->orderBy('views_num', 'desc')
                            ->orderBy('attention_num', 'desc')->orderBy('updated_at', 'desc')->skip(0)->take(4)->get();
        if (count($this->teachesHots) <= 0) {
            $this->teachesHots = Teaches::where(['is_validate' => 1])->orderBy('views_num', 'desc')
                                ->orderBy('attention_num', 'desc')->orderBy('updated_at', 'desc')->skip(0)->take(4)->get();
        }
        $this->ads = Ads::whereHas('getPositionName', function ($query) {
            $query->where('alias', '侧面');
        })->where(['app' => 'teaches'])->skip(0)->take(3)->get();
    }
    
    /**
     * 用户观看视频
     * @param Request $req
     */
    public function videoSee(Request $req)
    {
        $id = $req->input('teachesid',0);
        $contentid = $req->input('contentid',0);
        if(\Illuminate\Support\Facades\Request::ajax()){
            if(!$id)
                return $this->formatJson('2001',trans('front.param_error'));
            $result = Teaches::find($id);
            if(empty($result))
                return $this->formatJson('error',trans('front.exceptions'));
            $stcontent = TeachesContent::find($contentid);
            if( empty($stcontent) ||count($stcontent->chapter) <= 0 
                || count($stcontent->chapter->teaches) <= 0 
                || $stcontent->chapter->teaches->id != $id)
                return $this->formatJson('error',trans('front.exceptions'));
            if($stcontent->need_login == 1)
            {
                if(!Auth::check())
                    return $this->formatJson('2008',trans('front.no_login'));
                
                if($this->hasBuy($result, $stcontent)) //判断用户是否已经购买过该课程
                {
                    return $this->formatJson('success','开始学习',$stcontent,url($stcontent->video->url));
                }
                else 
                {
                    $userScore = UserScore::where('user_id','=',$this->user->id)->first();
                    if(!empty($stcontent->price) || $stcontent->price > 0)
                    {
                        if(empty($userScore))
                            return $this->formatJson('error',trans('front.score_to_lower'),'','/member/account');
                        if($stcontent->price > $userScore->score)
                            return $this->formatJson('error','front.score_to_lower','','/member/account');
                        $insert_user_teaches = array(
                            'user_id'   => $this->user->id,
                            'teaches_id'    => $id,
                            'chapter_id'    => $stcontent->chapter->id,
                            'content_id'    => $stcontent->id,
                            'score'         => $stcontent->price
                        );
                    }
                    //查找学生信息
                    $studys = UserStudy::where(['user_id'=>$this->user->id,'app_id'=>$id])->orderBy('created_at','desc')->first();
                    //查找课程详情
                    $allTeaches = TeachesContent::teachesCount($result->id);
                    //课程数量
                    $teaches_count = count($allTeaches);
                    if(empty($studys))
                    {
                        $chapter = $stcontent->chapter;
                        if(count($chapter)>0)
                        {
                            $chapter_num = getKeyFromArr($allTeaches,$stcontent);
                            $insert_row = array(
                                'user_id'       => $this->user->id,
                                'app'           => 'teaches',
                                'app_id'        => $result->id,
                                'chapter_id'    => $chapter->id,
                                'content_id'    => $stcontent->id,
                                'chapter_num'   => $chapter_num,
                                'chapters'      => $teaches_count,
                                'price'         => $result->price,
                                'finished'      => 0,
                            );
                        }
                        else 
                        {
                            return $this->formatJson('error',trans('front.param_error'));
                        }
                        DB::beginTransaction();
                        try{
                            UserStudy::firstOrCreate($insert_row);
                            $this->addStream($stcontent, $userScore, $result);
                            $result->incrementAdd('studys_num',1);
                            DB::commit();
                            return $this->formatJson('success','开始学习［'.$chapter->name.']'.$stcontent->name,$stcontent,url($stcontent->video->url));
                        }catch (\PDOException $e){
                            Log::info(['用户学习课程积分消费失败'=>$e->getMessage()]);
                            DB::rollBack();
                            return $this->formatJson('error','异常错误！');
                        }
                    }
                    else
                    {
                        $chapter = $stcontent->chapter;
                        if(count($chapter)>0)
                        {
                            if($stcontent->id > $studys->content_id)
                            {
                                $now_content = getKeyFromArr($allTeaches,$stcontent);
                                $now_content_id = $stcontent->id;
                                $now_chapter_id = $chapter->id;
                                $chapter_num = $now_content+1;
                            }
                            else
                            {
                                $now_content_id = $studys->content_id;
                                $now_chapter_id = $studys->chapter_id;
                                $chapter_num = $studys->chapter_num;
                            }
                        }
                        else 
                        {
                            return $this->formatJson('error',trans('front.param_error'));
                        }
                        $studys->chapter_id = $now_chapter_id;
                        $studys->content_id = $now_content_id;
                        $studys->chapter_num = $chapter_num;
                        $studys->chapters = $teaches_count;
                        DB::beginTransaction();
                        //异常处理
                        try{
                            $this->addStream($stcontent, $userScore, $result);
                            $studys->save();
                            DB::commit();
                        }catch (\PDOException $e){
                            Log::info(['用户学习失败'=>$e->getMessage()]);
                            DB::rollBack();
                            return $this->formatJson('error',trans('front.exceptions'));
                        }
                        return $this->formatJson('success','开始学习［'.$chapter->name.']'.$stcontent->name,$stcontent,url('/teaches/study/info'));
                    }
                }
            }
            else
            {
                return $this->formatJson('success','开始学习',$stcontent,url($stcontent->video->url));
            }
        }
    }
    
    /**
     * @author Joker
     * 检查用户是否可以直接观看视频
     * @param Request $req
     */
    public function checkTeaches(Request $req)
    {
        $teachesid = $req->input('teachesid',0);
        $contentid = $req->input('contentid',0);
        if(\Illuminate\Support\Facades\Request::ajax())
        {
            if(empty($teachesid))
            {
                return $this->formatJson('error',trans('front.param_error'));
            }
            
            $teaches = Teaches::find($teachesid);
            if(empty($contentid))
            {
                $chapter = TeachesChapter::where('teaches_id','=',$teaches->id)->orderBy('id','asc')->first();
                if(empty($chapter)) return $this->formatJson('error',trans('front.param_error'));
                $stcontent = TeachesContent::where('chapter_id','=',$chapter->id)->orderBy('id','ASC')->first();
                if(empty($stcontent)) return $this->formatJson('error',trans('front.param_error'));;
                $chapter_num = 1;
                if($stcontent->need_login == 1 && !Auth::check())
                {
                    return $this->formatJson('2008',trans('front.no_login'));
                }
            }
            else
            {
                $stcontent = TeachesContent::find($contentid);
                if(empty($stcontent) ||count($stcontent->chapter) <= 0|| count($stcontent->chapter->teaches) <= 0|| $stcontent->chapter->teaches->id != $teachesid)
                {
                    return $this->formatJson('error',trans('front.param_error'));
                }
            }
            if($stcontent->need_login == 1 && !Auth::check())
            {
                return $this->formatJson('2008',trans('front.no_login'));
            }
            return $this->formatJson('success','开始学习［' . $stcontent->chapter->name . ']' . $stcontent->name,
                        $stcontent, url('/teaches/study/'.$teachesid.'/'.$stcontent->id));
        }
    }
    
    /**
     * @param  $id 教程ID
     * @param  $contentid 课程ID
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function studyTeaches($id,$contentid)
    {
        //查找课程
        $result = Teaches::find($id);
        if(empty($result))
            abort(404);
        if(!empty($contentid) && $contentid > 0)
        {
            $stcontent = TeachesContent::find($contentid);
            if( empty($stcontent) ||count($stcontent->chapter) <= 0|| count($stcontent->chapter->teaches) <= 0|| $stcontent->chapter->teaches->id != $id)
                abort(404);
            if($stcontent->need_login == 1)
            {
                if(!Auth::check())
                {
                    return redirect()->to('/teaches/'.$id)
                            ->withErrors([ 'errCode' => 2008,'message'=>'学习该课程请先登录，谢谢！' ]);
                }
                $userScore = UserScore::where('user_id','=',$this->user->id)->first();
                if(!$this->hasBuy($result, $stcontent)) //判断用户是否已经购买过该课程
                {
                    if(!empty($stcontent->price) || $stcontent->price > 0)
                    {
                        if(empty($userScore) || $stcontent->price > $userScore->score)
                        {
                            return redirect()->to('/member/account')
                                    ->withErrors(['message'=>'您的积分不足，请先充值！' ]);
                        }
                    }
                }
                //查找学生信息
                $studys = UserStudy::where(['user_id'=>$this->user->id,'app_id'=>$id])->orderBy('created_at','desc')->first();
                //查找课程详情
                $allTeaches = TeachesContent::teachesCount($result->id);
                //如果没有找到学生信息
                return $this->userStudy($result, $studys, $stcontent, $allTeaches, $contentid, $userScore);
            }
            else 
            {
                return $this->studyinfo($stcontent);
            }
        }
        else 
        {
            //用户登录与否的业务逻辑不一致
            if(Auth::check())
            {
                $userScore = UserScore::where('user_id','=',$this->user->id)->first();
                $studys = UserStudy::where(['user_id'=>$this->user->id,'app_id'=>$id])->orderBy('created_at','desc')->first();
                //查找课程详情
                $allTeaches = TeachesContent::teachesCount($result->id);
                return $this->userStudy($result, $studys, '', $allTeaches, 0, $userScore);
            }
            else 
            {
                $chapter = TeachesChapter::where('teaches_id','=',$result->id)->orderBy('id','asc')->first();
                if(empty($chapter)) abort(404);
                $stcontent = TeachesContent::where('chapter_id','=',$chapter->id)->orderBy('id','ASC')->first();
                if(empty($stcontent)) abort(404);
                $chapter_num = 1;
                if($stcontent->need_login == 1)
                {
                    return redirect()->to('/teaches/'.$id)
                        ->withErrors([ 'errCode' => 2008,'message'=>'学习该课程请先登录，谢谢！' ]);
                }
                return $this->studyinfo($stcontent);
            }
        }
    }
    
    /**
     * @param  $teaches  课程
     * @param  $studys 学习记录
     * @param  $stcontent 教程
     * @param  $allTeaches 该课程下所有的教程
     * @param integer  $contentid 教程编号
     * @param  $userScore 当前登录用的积分
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    private function userStudy($teaches,$studys,$stcontent,$allTeaches,$contentid,$userScore)
    {
        $teaches_count = count($allTeaches);
        if(empty($studys))
        {
            if($contentid>0)
            {
                $chapter = $stcontent->chapter;
                if(empty($chapter)) abort(404);
                $chapter_num = getKeyFromArr($allTeaches,$stcontent);
            }
            else 
            {
                $chapter = TeachesChapter::where('teaches_id','=',$teaches->id)->orderBy('id','asc')->first();
                if(empty($chapter)) abort(404);
                $stcontent = TeachesContent::where('chapter_id','=',$chapter->id)->orderBy('id','ASC')->first();
                if(empty($stcontent)) abort(404);
                $chapter_num = 1;
            }
            if(!$this->hasBuy($teaches, $stcontent)) //判断用户是否已经购买过该课程
            {
                if(empty($userScore) || $stcontent->price > $userScore->score)
                {
                    return redirect()->to('/member/account')
                            ->withErrors(['message'=>'您的积分不足，请先充值！' ]);
                }
            }
            $insert_row = array(
                'user_id'       => $this->user->id,
                'app'           => 'teaches',
                'app_id'        => $teaches->id,
                'chapter_id'    => $chapter->id,
                'content_id'    => $stcontent->id,
                'chapter_num'   => $chapter_num,
                'chapters'      => $teaches_count,
                'price'         => $stcontent->price,
                'finished'      => 0,
            );
            DB::beginTransaction();
            try{
                $this->addStream($stcontent, $userScore,$teaches);
                UserStudy::firstOrCreate($insert_row);
                $teaches->incrementAdd('studys_num',1);
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['用户学习课程积分消费失败'=>$e->getMessage()]);
                DB::rollBack();
                abort(404);
            }
            return $this->studyinfo($stcontent);
        }
        else
        {
            if($contentid>0 && is_numeric($contentid))
            {
                //章节号
                $chapter = $stcontent->chapter;
                if(empty($chapter)) abort(404);
                if($stcontent->id > $studys->content_id)
                {
                    $now_content = getKeyFromArr($allTeaches,$stcontent);
                    $now_content_id = $stcontent->id;
                    $now_chapter_id = $chapter->id;
                    $chapter_num = $now_content+1;
                }
                else
                {
                    $now_content_id = $studys->content_id;
                    $now_chapter_id = $studys->chapter_id;
                    $chapter_num = $studys->chapter_num;
                }
            }
            else
            {
                $stcontent = TeachesContent::where('chapter_id','=',$studys->chapter_id)->where('id','>',$studys->content_id)->first();
                if(empty($stcontent))
                {
                    $chapter = TeachesChapter::where('teaches_id','=',$teaches->id)->where('id','>',$studys->chapter_id)->first();
                    if(empty($chapter))
                    {
                        $chapter = TeachesChapter::where('teaches_id','=',$teaches->id)->where('id','=',$studys->chapter_id)->first();
                        $stcontent = TeachesContent::where('chapter_id','=',$studys->chapter_id)->where('id','=',$studys->content_id)->first();
                    }
                    else
                    {
                        $stcontent = TeachesContent::where('chapter_id','=',$chapter->id)->orderBy('id','ASC')->first();
                    }
                }
        
                $chapter = TeachesChapter::where('id','=',$stcontent->chapter_id)->first();
                $now_content = getKeyFromArr($allTeaches,$stcontent);
                $now_content_id = $stcontent->id;
                $now_chapter_id = $chapter->id;
                $chapter_num = $now_content+1;
            }
            if(!$this->hasBuy($teaches, $stcontent)) //判断用户是否已经购买过该课程
            {
                if(empty($userScore) || $stcontent->price > $userScore->score)
                {
                    return redirect()->to('/member/account')
                        ->withErrors(['message'=>'您的积分不足，请先充值！' ]);
                }
            }
            $studys->chapter_id = $now_chapter_id;
            $studys->content_id = $now_content_id;
            $studys->chapter_num = $chapter_num;
            $studys->chapters = $teaches_count;
            //异常处理
            DB::beginTransaction();
            try{
                $this->addStream($stcontent, $userScore,$teaches);
                $studys->save();
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['用户学习失败'=>$e->getMessage()]);
                DB::rollBack();
                abort(404);
            }
            return $this->studyinfo($stcontent);
        }
    }
    
    /**
     * @param  $result 课程内容
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    private function studyinfo($result)
    {
        $result->incrementAdd('views_num', 1);
        $teaches = $result->chapter->teaches;
        $secondid = 0;
        $lastid = 0;
        $nowCate = 0;
        $name = '';
        $employTags = collect();
        if (count($teaches) > 0) {
            if (count($teaches->categorys) > 0) {
                $secondid = $teaches->categorys->pid;
            }
            $lastid = $teaches->cate_id;
            $nowCate = $teaches->id;
            $name = $result->name;
            $employTags = array();
            foreach ($teaches->tags as $etags) {
                $employTags[] = Tags::where('tags_id', '=', $etags->tags_id)->first()->tags_name;
            }
        }
        $comments = Comments::with(['childComments' => function ($query) {
            $query->orderBy('created_at', 'desc');
        }])->where(array('to_comment_id' => 0, 'app_table' => 'tcourse', 'app_id' => $result->id))->orderBy('created_at', 'desc')->get();
    
        $ucollect = $this->isCollected('teaches_content', $result->id);
        if (!empty($ucollect)) {
            $result->is_collect = 1;
        } else {
            $result->is_collect = 0;
        }
        $result->showtype = 'teaches';
    
        $chapterids = TeachesChapter::where('teaches_id', '=', $teaches->id)->lists('id');
        $result->nextid = TeachesContent::whereIn('chapter_id', $chapterids)->where('id', '>', $result->id)->orderBy('id', 'ASC')->first();
        $result->previd = TeachesContent::whereIn('chapter_id', $chapterids)->where('id', '<', $result->id)->orderBy('id', 'DESC')->first();
        $mianbaoxie = $this->mianbaoxie('teaches', 1, $secondid, $lastid, $nowCate, '充电加油', $name, 'show', '职场技能', 'study', $teaches->id, $teaches->name);
    
        switch ($result->teaches_type) {
            case 1:
                return view('front.teaches.video')->with('employTags', $employTags)->with('result', $result)->with('nav', $this->nav)->with('mianbaoxie', $mianbaoxie)->with('comments', $comments)->with('app_table', 'tcourse');
            case 2:
                return view('front.teaches.office')->with('employTags', $employTags)->with('result', $result)->with('nav', $this->nav)->with('mianbaoxie', $mianbaoxie)->with('comments', $comments)->with('app_table', 'tcourse');
            case 3:
                return view('front.teaches.ppt')
                ->with('employTags', $employTags)
                ->with('result', $result)
                ->with('nav', $this->nav)
                ->with('mianbaoxie', $mianbaoxie)
                ->with('comments', $comments)
                ->with('app_table', 'tcourse');
            case 4://修改4/8自定义模块
                $result->description = unserialize($result->description);
                $result->content = unserialize($result->content);
                return view('front.teaches.course')
                        ->with('employTags', $employTags)
                        ->with('result', $result)
                        ->with('nav', $this->nav)
                        ->with('mianbaoxie', $mianbaoxie)
                        ->with('comments', $comments)
                        ->with('app_table', 'tcourse');
            default:
                $result->description = unserialize($result->description);
                $result->content = unserialize($result->content);
                $smallImg = array();
                $isNew = 0;
                $allcount = 0;
    
                //判断title 是否在 数组中 遍历
                if (array_key_exists('title', $result->content[0])) {
                    $isNew = 1;
                    foreach ($result->content as $firstcon) {
                        ++$allcount;
                        $allcount += count($firstcon['content']);
                        foreach ($firstcon['content'] as $con) {
                            if (count($smallImg) > 6) {
                                break;
                            } else {
                                if (!empty($con['img']))
                                    $smallImg[] = $con['img'][0];
                            }
                        }
                    }
                } else {
                    $isNew = 0;
                    $allcount = count($result->content);
                    foreach ($result->content as $con) {
                        if (count($smallImg) > 6) {
                            break;
                        } else {
                            if (!empty($con['img']))
                                $smallImg[] = $con['img'][0];
                        }
                    }
                }
    
                $result->notice = unserialize($result->notice);
                $result->tools = unserialize($result->tools);
    
                return view('front.teaches.step')
                        ->with('result', $result)
                        ->with('employTags', $employTags)
                        ->with('isnew', $isNew)
                        ->with('allcount', $allcount)
                        ->with('ads_img', $this->ads)
                        ->with('teaches_hot', $this->teachesHots)
                        ->with('mianbaoxie', $mianbaoxie)
                        ->with('comments', $comments)
                        ->with('smallImg', $smallImg)
                        ->with('app_table', 'tcourse')
                        ->with('nav', $this->nav);
        }
    }
    
    /**
     * @param  $stcontent 课程
     * @param  $userScore 用户积分数组
     * @param  $teaches 教程
     */
    private function addStream($stcontent,$userScore,$teaches)
    {
        if($stcontent->price > 0 && !$this->hasBuy($teaches, $stcontent))
        {
            $insert_stream = array(
                'user_id'       => $this->user->id,
                'action'        => 'study',
                'action_url'    => '/teaches/study/'.$stcontent->id,
                'type'          => 0,
                'scores'        => -$stcontent->price,
                'is_read'       => 0
            );
            UserScoreStream::firstOrCreate($insert_stream);
            $insert_user_teaches = array(
                'user_id'       => $this->user->id,
                'teaches_id'    => $teaches->id,
                'chapter_id'    => $stcontent->chapter->id,
                'content_id'    => $stcontent->id,
                'score'         => $stcontent->price
            );
            UserTeaches::firstOrCreate($insert_user_teaches);
            $userScore->score = $userScore->score - $stcontent->price;
            $userScore->save();
        }
    }
    
    /**
     * @param  $teaches 教程   
     * @param  $stcontent 课程
     * @return boolean
     */
    private function hasBuy($teaches,$stcontent)
    {
        $buyContent = UserTeaches::where(array('user_id'=>$this->user->id,'teaches_id'=>$teaches->id,'chapter_id'=>$stcontent->chapter->id,'content_id'=>$stcontent->id))->first();
        $buyChapter = UserTeaches::where(array('user_id'=>$this->user->id,'teaches_id'=>$teaches->id,'chapter_id'=>$stcontent->chapter->id,'content_id'=>0))->first();
        $buyTeaches = UserTeaches::where(array('user_id'=>$this->user->id,'teaches_id'=>$teaches->id,'chapter_id'=>0,'content_id'=>0))->first();
        if(empty($buyContent) && empty($buyChapter) && empty($buyTeaches))
        {
            return FALSE;
        }
        else 
        {
            return TRUE;
        }
    }
}